<?php

require_once('CustomQuery.class.php');

class ResultsetPager extends sfPager {

    protected
	    $countQuery = '',
	    $connection = null,
	    $query = '';
    
	public function __construct($cSQL, $SQL, $class = null, $maxPerPage = 10) {


		$this->connection = Propel::getConnection();
        $this->setQuery(new CustomQuery($SQL));
        $this->setCountQuery($cSQL);
        $this->setMaxPerPage($maxPerPage);
        $this->setPage(1);
		
        if($class) {
			parent::__construct($class, $maxPerPage);
		}        
	}

	public function init() {
	    $hasMaxRecordLimit = ($this->getMaxRecordLimit() !== false);
		$maxRecordLimit = $this->getMaxRecordLimit();
	    
        $cForCount =  $this->getCountQueryResults();
        
        $c = $cForCount->fetchObject();
        $count = $c->count;
        
        $this->setNbResults($hasMaxRecordLimit ? min($count, $maxRecordLimit) : $count);
 
        $c =  $this->getQuery();
        $c->setLimit(0);
        $c->setOffset(0);
        if (($this->getPage() == 0 || $this->getMaxPerPage() == 0)) {
            $this->setLastPage(0);
        } else {
            $this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
            $c->setOffset(($this->getPage() - 1) * $this->getMaxPerPage());
            if ($hasMaxRecordLimit) {
				$maxRecordLimit = $maxRecordLimit - $offset;
				if ($maxRecordLimit > $this->getMaxPerPage()) {
					$c->setLimit($this->getMaxPerPage());
				} else {
					$c->setLimit($maxRecordLimit);
				}
			} else {
				$c->setLimit($this->getMaxPerPage());
			}
        }

	}

	protected function retrieveObject($offset) {
	    $cForRetrieve = $this->getQuery();
	    $cForRetrieve->setOffset($offset - 1);
	    $cForRetrieve->setLimit(1);
	    $cForRetrieve->execute();
	    return $cForRetrieve;
	}

	public function getResults() {
	    
	    $c = $this->connection->prepare($this->getQuery()->getQuery());
		$c->execute();
		if($this->class != '') {
		    return call_user_func(array($this->getClassPeer(), 'populateObjects'), $c);
		} else {
		    return $c;
		}
	}

	public function getCountQuery() {
	    return $this->countQuery;
	}
	
	public function setCountQuery($c) {
	    $this->countQuery = $c;
	}
	
	public function getCountQueryResults() {
	    $c = $this->connection->prepare($this->getCountQuery());
	    $c->execute();
	    return $c;
	}
	
	public function getQuery() {
	    return $this->query;
	}
	
	public function setQuery($c) {
	    $this->query = $c;
	}

	public function getClassPeer() {
	    return constant($this->class.'::PEER');
	}
}


